<?php
namespace application\depend;

/**
 * mysql 数据库
 * 数据库核心类
 */
//use app\initcore\Appreturn;
class Dbiov{
	
	public $pdo;
	private static $_instance = null;
	public $table;       //要操作的表
    public $presqlErrInfo = null;

	private function __construct(){
		$host = 'localhost';
		$dbname = 'xingai';
		$user = 'root';
		$pas = 'dj19870523';
		$port = '3306';
		try{
            $this->pdo = null;
			$this->pdo = new \PDO("mysql:host=$host;dbname=$dbname;port=$port",$user,$pas);
			$this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
			$this->pdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_NATURAL);   //自动
			$this->pdo->query("set names utf8");			
		}catch(\PDOException $e){
				$data['pdo_err'] = $e->getMessage();
				$data['pdo_e'] = $e->__toString();
				$data['get_wrong'] = '初始化 MYSQL 出错了';
			//	appLog::appLog('error',$data);
			$this->pdo = null;
           		// Appreturn::errorReturn(ERR_DB_CON_ERROR);   //直接退出算了
		}

	}
	
	public static function getInstance(){
		if(self::$_instance === null){
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * PDO prepare
	 */
	public function prepareSql($sql){
		return	$this->pdo->prepare($sql);
	}

	public function rollback(){
        $this->pdo->inTransaction() && $this->pdo->rollBack();
    }

    /**
     * 事务
     */
    public function trans(){
        $this->pdo->setAttribute(\PDO::ATTR_AUTOCOMMIT,0);
       return  $this->pdo->beginTransaction();
    }
    /**
     * @param string $table 表名
     * @param array $data  字段名与数值
     * 新增一条数据
     * 2018.2.22 新增
     * 成功返回 新增的ID
     * 失败返回  false 错误信息在 $presqlErrInfo
     * 没有数据库连接 或者 参数非法 返回 null
     */
    public function insert($table = "",$data = []){
        if(null === $this->pdo) return null;
        if(empty($table)){
            $this->presqlErrInfo = "请先指定表名！";
            return null;
        }
        if(empty($data) || !is_array($data)){
            $this->presqlErrInfo = "新增数据必须是数组！";
            return null;
        }//end
        $key = "";
        $value = "";
        foreach($data as $k => $v){
            $key .= $k.",";
            $value .= ":".$k.",";
        }//end foreach
        $key = rtrim($key,",");
        $value = rtrim($value,",");

        $sql = "insert into $table ($key) values ($value)";
        $presql = $this->prepareSql($sql);
        $this->bindValue($presql,$data);
        $ret = $presql->execute();
        if(false === $ret){
            $this->presqlErrInfo = $presql->errorInfo();
            return false;
        }
        $newid = $this->pdo->lastInsertId($presql);
        return $newid;
    }//end

    /**
     * @param $presql
     * @param $data  数组形式
     * 为SQL绑定变量
     */
    public function bindValue(&$presql,$data){
        if(!is_array($data) || empty($data)){

        }else {
            foreach ($data as $k => $v) {
                $presql->bindValue(':' . $k, $v);
            }
        }
    }//end

    /**
     * 提交事务
     */
    public function commit(){
        $this->pdo->commit();
    }

    //关闭连接
    public function closeDb(){
        $this->pdo = null;
        self::$_instance = null;
    }

    /**
     * 查询结果集
     */
    public function select(&$presql = ""){
        if($presql->execute()){
            $ret = $presql->fetchAll();
            return $ret;
        }
        return false;   //出错
    }//end

    //快捷函数-返回查询语句结果集(select)
    public function selectResult($sql = "", $data = []){
    
        $presql = $this->prepareSql($sql);
        if (is_array($data) && !empty($data)) {
            $this->bindValue($presql, $data);
        }
        return $this->select($presql);
    }
    
}//end class
